/**
 * Created by vincent on 2017/4/11.
 */
function s2ab(s) {
    if (typeof ArrayBuffer !== 'undefined') {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
    } else {
        var buf = new Array(s.length);
        for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
        return buf;
    }
}

function array2aoa(array) {
    if (Array.isArray(array) && array.length > 0) {
        var aoa = [];
        var headTemp = {};
        angular.forEach(array, function (temp) {
            if (Object.keys(temp).length > Object.keys(headTemp).length) {
                headTemp = temp;
            }
        });
        var aoaHead = Object.keys(headTemp);
        aoa.push(aoaHead);
        angular.forEach(array, function (temp) {
            var dataTemp = [];
            angular.forEach(aoaHead, function (headTemp) {
                if (temp[headTemp] != null && temp[headTemp] != undefined) {
                    dataTemp.push(temp[headTemp].toString());
                } else {
                    dataTemp.push("");
                }
            });
            aoa.push(dataTemp);
        });
        return aoa;
    } else {
        return [];
    }
}

function sheet_to_workbook(sheet, opts) {
    var n = opts && opts.sheet ? opts.sheet : "Sheet1";
    var sheets = {};
    sheets[n] = sheet;
    return {SheetNames: [n], Sheets: sheets};
}

function export_wb_to_excel(wb, type, fn) {
    //var wb = XLSX.utils.table_to_book(document.getElementById(id), {sheet:"Sheet JS"});
    var wbout = XLSX.write(wb, {bookType: type, bookSST: true, type: 'binary'});
    var fname = fn || 'test.' + type;
    try {
        saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), fname);
    } catch (e) {
        if (typeof console != 'undefined') console.log(e, wbout);
    }
    return wbout;
}


